const app = getApp()
const common = require('../common');
const utils = require('../../utils/util.js');
let Connection = null, RTC = null;

wx.setKeepScreenOn({
  keepScreenOn: true
})

let errorHandler = (error) => {
  error = error || { msg: '失败了', code: 50000 }
  console.log(error)
  if ([50000, 50051, 50052, -1307].includes(error.code)) {
    setTimeout(() => {
      wx.navigateBack({
        delta: 2
      })
    }, 2000);
  }
  wx.hideLoading();
  common.showToast(error.msg || '')
};
Page({
  data: {
    roomId: '',
    userId: '',
    inviteUserIds: '',
    pusher: null,
    players: [],
    timer: 0,
    interval: 0,
    enableCamera: true
  },
  radioChange(event){
    console.log(event)
    this.setData({
      enableCamera: event.detail.value == 1
    });
  },
  startTimer() {
    var context = this;
    var interval = setInterval(() => {
      var date = new Date();
      var hour = date.getHours();
      var time = date.getTime();
      var m = date.getMinutes();
      var s = Math.floor(time / 1000 % 60);
      var ms = Math.floor(time % 1000);
      ms = ms < 100 ? "0" + ms : ms;
      s = s < 10 ? "0" + s : s;
      m = m < 10 ? "0" + m : m;
      hour = hour < 10 ? "0" + hour : hour;
      context.setData({
        timer: `${hour}:${m}:${s}:${ms}`
      })
    }, 50)
    context.setData({
      interval
    })
  },
  join: function () {
    let { data: { userId, enableCamera } } = this;
    wx.showLoading({
      title: '加入中...',
      mask: true
    });
    var timer = setTimeout(() => {
      wx.hideLoading();
    }, 10000);
    RTC.join({
      id: userId,
      name: userId,
      mediaType: enableCamera ? 2 : 0,
    }).then(() => {
      wx.hideLoading();
      clearTimeout(timer);
      common.showToast('Join Successfully')
    }, errorHandler);
  },
  leave: function () {
    let { data: { userId } } = this;
    this.setData({
      players: [],
      pusher: null
    })
    RTC.leave({ id: userId }).then(() => {
      common.showToast('Leave Successfully')
    }, errorHandler);
  },
  mute: function () {
    let { data: { userId } } = this;
    let pusherContext = wx.createLivePusherContext();
    pusherContext.setMICVolume({
      volume: 0,
      fail: function(){
        common.showToast('setMICVolume 0 fail')
      },
      success: function(){
        RTC.mute({ id: userId }).then(() => {
          common.showToast('Mute Successfully')
        }, errorHandler);
      }
    })
  },
  unmute: function () {
    let pusherContext = wx.createLivePusherContext();
    let { data: { userId } } = this;
    pusherContext.setMICVolume({
      volume: 1,
      fail: function () {
        common.showToast('setMICVolume 1 fail')
      },
      success: function () {
        RTC.unmute({ id: userId }).then(() => {
          common.showToast('Unmute Successfully')
        }, errorHandler);
      }
    })
  },
  disable: function () {
    let { data: { userId } } = this;
    RTC.disable({ id: userId }).then(() => {
      common.showToast('Disable Successfully')
    }, errorHandler);
  },
  enable: function () {
    let { data: { userId } } = this;
    RTC.enable({ id: userId }).then(() => {
      common.showToast('Enable Successfully')
    }, errorHandler);
  },
  start: function(){
    this.startTimer();
  },
  stop: function(){
    clearInterval(this.data.interval)
  },
  onUnload: function(){
    
    let { data: { userId } } = this;
    this.setData({
      players: [],
      pusher: null
    })
    RTC.leave({ id: userId }).then(() => {
      Connection.disconnect();
    }, () => {
      Connection.disconnect();
    });
  },
  onLoad: function (options) {
    let context = this;
    let { globalData: { $services } } = app;
    Connection = $services.Connection;
    RTC = $services.RTC;

    let { token, userId, groupId, roomId } = options;
    wx.setNavigationBarTitle({
      title: `${roomId} - ${userId}`
    })
    this.setData({
      roomId: roomId,
      userId: userId
    });
    token = decodeURIComponent(token);
    wx.showLoading({
      title: '连接中...',
      // mask: true
    });
    var timer = setTimeout(() => {
      wx.navigateBack({
        delta: 2
      });
      wx.hideLoading();
    }, 10000);
    Connection.connect({ token }).then(() => {
      clearTimeout(timer);
      wx.hideLoading();
      common.showToast(`连接成功`)
    });
    RTC.init({
      id: roomId
    });
    RTC.memberWatch(({ type, user, error }) => {
      if (utils.isEqual(type, 'joined')) {
        common.showToast(`${user.id} joined`);
      }
      if (utils.isEqual(type, 'left')) {
        common.showToast(`${user.id} left`);
        let { data: { players } } = context;
        console.log(players, user)
        players = players.filter((player) => {
          return !utils.isEqual(player.id, user.id);
        });
        context.setData({
          players: players
        })
      }
      if (utils.isEqual(type, 'error')){
        errorHandler(error)
      }
    });
    RTC.streamWatch(({ type, user, isSelf }) => {
      let { data: { players = [] } } = context;
      if (utils.isEqual(type, 'published')) {
        if (isSelf) {
          context.setData({
            pusher: user
          })
        } else {
          for(let i = 0; i < players.length; i++){
            let player = players[i];
            if (utils.isEqual(player.id, user.id)){
              players.splice(i, 1);
              break;
            }
          }
          context.setData({
            players: players
          })

          setTimeout(() => {
            players.push(user)
            context.setData({
              players: players
            })
          }, 200)
        }
      }
      common.showToast(`${user.id} ${type}`)
    });
  },
  statechange(e) {
    const code = e.detail.code;
    console.log('live-pusher code:', code);
    if (code === -1307) {
      const livepusher = wx.createLivePusherContext();
      if (livepusher) {
        console.warn('尝试重启推流...');
        console.warn('停止当前推流...');
        livepusher.stop({
          fail(res) {
            console.error('停止推流失败...', res);
          },
          success() {
            console.warn('重新开始推流...');
            livepusher.start({
              fail(res) {
                console.error('推流失败', res);
              },
              success() {
                console.warn('推流已恢复');
              }
            });
          }
        });
      }
    }
  }
});